//
//  ViewController.m
//  MusicForChilden
//
//  Created by qlydfb on 2021/10/28.
//

#import "ViewController.h"
#import <MJRefresh.h>
#import "FBHomeVideoListTableViewCell.h"
#import "FBVideoDetailMdeol.h"
#import <FreeStreamer/FSAudioController.h>
#import "FBPlayView.h"
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(strong, nonatomic)NSMutableArray *listArrData;
@property(strong,nonatomic)UITableView *listTable;
@property(assign, nonatomic)NSInteger pageNO;
@property(strong, nonatomic)FSAudioController *audioController;
@property(strong, nonatomic)FBPlayView *playView;
@property(assign,nonatomic)NSInteger currentIndex;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self initWithView];
    // Do any additional setup after loading the view.
}
- (void)testData{
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"dd.html" ofType:nil];
    NSString *repose = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    
    NSRegularExpression * regular = [[NSRegularExpression alloc]initWithPattern:@"(\"ProgramStore\".*)window.ssr" options: NSRegularExpressionDotMatchesLineSeparators error:nil];
//__initStores=(.*?)window.ssr
 /*
   设置整体匹配范围 和 匹配属性 包含所写的正则表达式字符串。 t r
   (regular：当做一个被发现正则表达式）
   (htmlStr：当做一个检测文本)
   (NSMakeRange(0,htmlStr.length)：返回检测范围)
   简单的说就是匹配检测文本在指定范围里有多少个 符合正则表达式字符串 属性
 */
NSArray * htmlArray = [regular matchesInString:repose options:0 range:NSMakeRange(0, repose.length)];

   /*
     接下来遍历一下
     NSTextCheckingResult 是一个类用来描述项目位于通过文本检查。每个对象代表了一个请求的文本内容,被发现在分析文本块。
   */
   for (NSTextCheckingResult * match in htmlArray)
   {
     /*
      下面才开始进行匹配
      substringWithRange: 返回一个字符串对象,其中包含的字符的接收器在一个给定的范围内
      range: 返回结果的范围,接收方代表。
     */
     NSString * textStr = [repose substringWithRange: match.range];
       NSRange range = [textStr rangeOfString:@"window.ssr"];
       textStr = [NSString stringWithFormat:@"{%@",[textStr substringWithRange:NSMakeRange(0, range.location)]];
       NSDictionary *info = [NSJSONSerialization JSONObjectWithData:[textStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
       
       FBVideoDetailMdeol *mModel = [[FBVideoDetailMdeol alloc]initWithDictionary:info[@"ProgramStore"][@"programInfo"] error:nil];
       self.audioController = [[FSAudioController alloc]initWithUrl:[NSURL URLWithString:mModel.audioUrl]];
       [self.audioController play];
       self.audioController.onFailure = ^(FSAudioStreamError error, NSString *errorDescription) {
           NSLog(@"errorDescription = %@",errorDescription);

       };
       self.audioController.onStateChange = ^(FSAudioStreamState state) {
           NSLog(@"FSAudioStreamState = %zd",state);

       };
       self.audioController.onMetaDataAvailable = ^(NSDictionary *metadata) {
        NSLog(@"metadata = %@",metadata);
       };
       

       
   }
}
- (void)initWithView{
    
    self.listArrData = [NSMutableArray arrayWithCapacity:2];
    self.pageNO = 1;
    [self.view addSubview:self.playView] ;
    [self.playView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0)             ;
         make.top.mas_equalTo(self.mas_topLayoutGuide);
         make.height.mas_equalTo(260);
     }];
    __weak typeof(self) ws = self;
    self.playView.playAction = ^(NSInteger actionType) {
        if(actionType == 1) {
            if(ws.currentIndex -- < 0){
                
            }else{
                [ws requestVideoInfo:ws.currentIndex];
            }
        }else{
            if(ws.currentIndex ++ > ws.listArrData.count -1){
                
            }else{
                [ws requestVideoInfo:ws.currentIndex];
            }
        }
    };
    self.listTable = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.listTable.backgroundColor = [UIColor clearColor];
    self.listTable.delegate = self;
    self.listTable.dataSource = self;
    self.listTable.rowHeight = 70;
    [self.view addSubview:self.listTable];
    [self.listTable mas_makeConstraints:^(MASConstraintMaker *make) {
       make.left.right.mas_equalTo(0) ;
        make.top.mas_equalTo(self.playView.mas_bottom);
        make.bottom.mas_equalTo(self.mas_bottomLayoutGuide);
    }];
    [self.listTable registerClass:[FBHomeVideoListTableViewCell class] forCellReuseIdentifier:@"FBHomeVideoListTableViewCell"];
    self.listTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageNO = 1;
       [self requestData] ;
    }];
    self.listTable.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [self requestData];
    }];
    [self.listTable.mj_header beginRefreshing];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.listArrData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FBHomeVideoListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FBHomeVideoListTableViewCell" forIndexPath:indexPath];
    if(indexPath.row < _listArrData.count){
        [cell showCellModel:_listArrData[indexPath.row]];
    }
    
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.row < _listArrData.count){
        self.currentIndex = indexPath.row;
        [self requestVideoInfo:_currentIndex];
//        FBVideoListDetailMode *model =  _listArrData[indexPath.row];
//        __weak typeof(self) ws = self;
//        [FBVideoDetailMdeol getVideoDetail:@"418090" nameId:model.id success:^(FBVideoDetailMdeol * _Nonnull resultDict) {
//
//            [ws.playView playViewInfo:resultDict videoInfo:model];
//        } fail:^(NSError * _Nonnull error) {
//            ;
//        }];
    }
    
}
- (void)requestVideoInfo:(NSInteger)index{
    if(index < _listArrData.count){
        FBVideoListDetailMode *model =  _listArrData[index];
        __weak typeof(self) ws = self;
        [FBVideoDetailMdeol getVideoDetail:@"418090" nameId:model.id success:^(FBVideoDetailMdeol * _Nonnull resultDict) {
          
            [ws.playView playViewInfo:resultDict videoInfo:model];
        } fail:^(NSError * _Nonnull error) {
            ;
        }];
    }
}

- (void)requestData{
    [FBVideoListModel getVoiceListIndex:_pageNO andSuccess:^(NSArray * _Nonnull listArr, NSInteger total) {
        if(self.pageNO == 1){
            [self.listArrData removeAllObjects];
            [self.listArrData addObjectsFromArray:listArr];
        }
        [self.listArrData addObjectsFromArray:listArr];
        if(self.pageNO >= total){
            [self.listTable.mj_footer endRefreshingWithNoMoreData];
        }else{
            self.pageNO ++;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
           [self.listTable reloadData] ;
            [self.listTable.mj_header endRefreshing];
            [self.listTable.mj_footer endRefreshing];
        });
    } faile:^(NSError * _Nonnull error) {
        ;
    }];
}
- (UIView *)playView{
    if(!_playView){
        _playView = [[FBPlayView alloc]initWithFrame:self.view.bounds];
        _playView.backgroundColor = [UIColor whiteColor];
    }
    
    return _playView;
}
@end
